import {Component, Input, OnInit, ViewChild, ComponentFactoryResolver, OnDestroy } from '@angular/core';
import {AdDirective} from '../ad.directive';
import {ComponentFactoryBoundToModule} from '@angular/core/src/linker/component_factory_resolver';
import {AdItem} from './ad.item';
import {AdComponent} from './ad-component';

@Component({
  selector: 'app-ad-banner',
  templateUrl: './ad-banner.component.html',
  styleUrls: ['./ad-banner.component.css']
})
export class AdBannerComponent implements OnInit, OnDestroy {

  @Input() ads: AdItem[];
  currentIndex = -1;

  // 引用指令
  @ViewChild(AdDirective) addirective: AdDirective;
  internal: any;

  constructor(private componentFactoryResolve: ComponentFactoryResolver) { }

  ngOnInit() {
    this.loadComponents();
    this.getAdsData();
  }

  ngOnDestroy() {
   clearInterval(this.internal);
  }

  // 加载组件
  loadComponents() {
    this.currentIndex = (this.currentIndex + 1) % (this.ads.length);
    const  currentItem = this.ads[this.currentIndex];
    console.log(currentItem.component);
    // ComponentFactoryResolver 来为每个具体的组件解析出一个 ComponentFactory
    const componentFactory = this.componentFactoryResolve.resolveComponentFactory(currentItem.component);
    const viewcontainer = this.addirective.viewContainer;
    viewcontainer.clear();
    const createElement = viewcontainer.createComponent(componentFactory);
    (<AdComponent>createElement.instance).data = currentItem.data;
  }

  // 加载数据
  getAdsData() {
    this.internal = setInterval(() => {
      this.loadComponents();
    }, 3000);
  }

}


